<template>
  <a-modal :width="500" :visible="visible" title="设置列表" @ok="handleOk" @cancel="cancel">
    <a-form :labelCol="{ span: 7 }" :wrapperCol="{ span: 16 }">
      <a-form-item label="是否需要弹窗" v-bind="validateInfos.hasPopup">
        <a-radio-group v-model:value="modelRef.hasPopup">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <template v-if="modelRef.hasPopup === 1">
        <a-form-item label="弹窗类型" v-bind="validateInfos.type">
          <a-radio-group v-model:value="modelRef.type">
            <a-radio value="drawer">抽屉</a-radio>
            <a-radio value="modal">对话框</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="宽度" v-bind="validateInfos.width">
          <a-input placeholder="请输入弹窗宽度" v-model:value="modelRef.width" />
        </a-form-item>
      </template>
    </a-form>
    <template #footer>
      <a-button key="back" @click="cancel">返回</a-button>
      <a-button @click="resetParams">重置参数</a-button>
      <a-button key="submit" type="primary" @click="handleOk">保存</a-button>
    </template>
  </a-modal>
</template>
<script>
import { defineComponent, reactive, toRaw, toRefs } from 'vue';
import { useForm } from '@ant-design-vue/use';
import _ from 'lodash-es';
export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({
        type: 'drawer',
        width: '',
      }),
    },
  },
  emits: ['update:form', 'update:visible', 'add-column'],
  setup(props, { emit }) {
    const { form } = toRefs(props);
    const state = reactive({
      modelRef: _.cloneDeep(form.value),
      rulesRef: {
        hasPopup: [
          {
            required: true,
            message: '请选择是否需要弹窗',
            type: 'number',
          },
        ],
        type: [
          {
            validator() {
              if (state.modelRef.hasPopup === 1 && !state.modelRef.type) {
                return Promise.reject('分页大小不得为空');
              } else {
                return Promise.resolve();
              }
            },
            message: '请选择弹窗类型',
          },
        ],
      },
    });

    const { resetFields, validate, validateInfos } = useForm(state.modelRef, state.rulesRef);

    const handleOk = () => {
      validate()
        .then(() => {
          emit('update:form', _.cloneDeep(toRaw(state.modelRef)));
          emit('update:visible', false);
        })
        .catch(err => {
          console.log('error', err);
        });
    };

    const cancel = () => {
      emit('update:visible', false);
      resetFields();
    };

    const resetParams = () => {
      resetFields();
    };

    return {
      ...toRefs(state),
      validateInfos,
      resetParams,
      handleOk,
      cancel,
    };
  },
});
</script>
<style lang="less" scoped>
@import url('../index.less');
// TODO
</style>
